package com.fjzx.androidframe.base.activity;

import android.arch.lifecycle.ViewModel;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;

import com.fjzx.androidframe.base.annotation.injector.ViewModelInjector;
import com.fjzx.androidframe.global.entity.Resource;

/**
 * 基础Activity类
 *
 * @param <VM> 数据请求器
 * @author xiongyongcong
 */
public abstract class BaseActivity<VM extends ViewModel> extends BaseSimpleActivity {
    /**
     * 数据请求器
     **/
    protected VM mViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 初始化数据请求器
        initViewModel();
        // 初始化数据
        initData();
    }

    /**
     * 初始化数据请求器
     */
    private void initViewModel() {
        mViewModel = ViewModelProviders.of(this).get(ViewModelInjector.inject(this));
    }

    /**
     * ViewModel 回调
     *
     * @param resource
     */
    protected void handleResult(Resource<?> resource) {
        switch (resource.status) {
            case LOADING:
                handleLoading(resource.action, resource.loadingMsgId);
                break;
            case ERROR:
                handleError(resource.action, resource.errorMessage);
                break;
            case SUCCESS:
                handleSuccess(resource.action, resource.data);
                break;
            default:
                break;
        }
    }

    /**
     * ViewModel 错误回调
     *
     * @param action
     * @param message
     */
    protected void handleError(String action, String message) {
        hideProgress();
        showToast(message);
    }

    /**
     * ViewModel 加载中回调
     *
     * @param action
     * @param msgId
     */
    protected void handleLoading(String action, int msgId) {
        showProgress(msgId);
    }

    /**
     * ViewModel 成功回调
     *
     * @param action
     * @param data
     */
    protected <T> void handleSuccess(String action, T data) {
        hideProgress();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        release();
    }

    /**
     * 子类重写该方法，释放资源
     */
    protected void release() {
    }

    /**
     * 子类重写此方法，初始化View
     */
    @Override
    abstract protected void initView();

    /**
     * 子类重写该方法，请求数据
     */
    abstract protected void initData();

}
